<template>
  <div class="food-card">
    <!-- 商品图片 -->
    <img class="food-img" :src="foodImg" alt="商品图" />
    <!-- 商品信息区域 -->
    <div class="food-info">
      <h3 class="food-title">{{ foodTitle }}</h3>
      <p class="food-price">¥ {{ foodPrice }}</p>
      <!-- 收藏按钮 -->
      <button class="favorite-btn" @click="toggleFavorite">
        <span :class="{ 'text-yellow-500': isFavorite }">
          {{ isFavorite ? '★' : '☆' }}
        </span>
        {{ isFavorite ? '已收藏' : '收藏' }}
      </button>
      <!-- 评分与月售等信息 -->
      <div class="sales-rating">
        <span class="rating-star">★★★★★</span>
        月售 {{ monthSales }}
      </div>
      <!-- 数量加减与加入购物车 -->
      <div class="count-area">
        <button class="count-btn" @click="decrement">-</button>
        <input class="count-input" type="number" v-model.number="count" min="1" />
        <button class="count-btn" @click="increment">+</button>
        <button class="add-cart-btn" @click="addToCart">加入购物车</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import {
  ref,
  onMounted,
  watch
} from 'vue';
import {
  useRoute,
  useRouter
} from 'vue-router';
import {
  showToast
} from 'vant'; // 引入Toast提示组件
import products from '@/data/products.js'; // 引入商品数据

const route = useRoute();
const router = useRouter();
const id = parseInt(route.params.id);

// 商品基础信息
const foodTitle = ref('');
const foodPrice = ref(0);
const foodImg = ref('');
const monthSales = ref(0);
const minOrder = ref(20);


// 交互状态
const isFavorite = ref(false);
const count = ref(1);
const isAdding = ref(false); // 加入购物车加载状态

// 从本地存储获取购物车数据
const getCartFromStorage = () => {
  return JSON.parse(localStorage.getItem('cart') || '[]');
};

// 保存购物车到本地存储
const saveCartToStorage = (cart) => {
  localStorage.setItem('cart', JSON.stringify(cart));
};

// 根据 id 查找商品信息
onMounted(() => {
  const product = products.find(item => item.id === id);
  if (product) {
    foodTitle.value = product.title;
    foodPrice.value = product.price;
    foodImg.value = product.pic;
    monthSales.value = product.soldCount;
  } else {
    router.push('/404'); // 商品不存在时跳转404页面
  }

  // 加载收藏状态和购物车数量
  loadFavoriteStatus();
  loadCartcount();
});

// 加载收藏状态
const loadFavoriteStatus = () => {
  const favorites = JSON.parse(localStorage.getItem('favorites') || '[]');
  isFavorite.value = favorites.some(item => item.id === id);
};

// 保存收藏状态
const saveFavoriteStatus = (isFavorited) => {
  let favorites = JSON.parse(localStorage.getItem('favorites') || '[]');

  if (isFavorited) {
    // 添加到收藏
    if (!favorites.some(item => item.id === id)) {
      favorites.push({
        id,
        title: foodTitle.value,
        price: foodPrice.value,
        pic: foodImg.value
      });
    }
  } else {
    // 从收藏中移除
    const index = favorites.findIndex(item => item.id === id);
    if (index !== -1) {
      favorites.splice(index, 1);
    }
  }

  localStorage.setItem('favorites', JSON.stringify(favorites));
};

// 切换收藏状态
const toggleFavorite = () => {
  isFavorite.value = !isFavorite.value;
  saveFavoriteStatus(isFavorite.value);
};

// 减少数量
const decrement = () => {
  if (count.value > 1) {
    count.value--;
  }
};

// 增加数量
const increment = () => {
  count.value++;
};

// 加载购物车中该商品的数量（用于更新已加入状态）
const loadCartcount = () => {
  const cart = getCartFromStorage();
  const cartItem = cart.find(item => item.id === id);
  if (cartItem) {
    // 这里可以处理已加入购物车的状态提示
  }
};

// 加入购物车核心功能
const addToCart = async () => {
  // 防重复点击
  if (isAdding.value) return;

  // 表单验证
  if (count.value <= 0) {
    showToast('请选择购买数量');
    return;
  }

  try {
    // 显示加载状态
    isAdding.value = true;

    // 模拟API请求延迟（实际开发中替换为真实接口调用）
    await new Promise(resolve => setTimeout(resolve, 800));

    // 获取当前购物车数据
    let cart = getCartFromStorage();

    // 检查商品是否已在购物车中
    const cartItemIndex = cart.findIndex(item => item.id === id);

    if (cartItemIndex !== -1) {
      // 已存在则更新数量
      cart[cartItemIndex].count += count.value;
    } else {
      // 不存在则添加新商品
      cart.push({
        id,
        title: foodTitle.value,
        price: foodPrice.value,
        pic: foodImg.value,
        count: count.value,
        selected: true // 默认选中
      });
    }

    // 保存购物车到本地存储
    saveCartToStorage(cart);

    // 显示成功提示
    showToast({
      message: `已将 ${count.value} 份 ${foodTitle.value} 加入购物车`,
      duration: 2000,
      type: 'success'
    });

    // 重置数量（可选）
    count.value = 1;

  } catch (error) {
    // 错误处理
    console.error('加入购物车失败', error);
    showToast('加入购物车失败，请稍后重试');
  } finally {
    // 隐藏加载状态
    isAdding.value = false;
  }
};
</script>

<style scoped>
.food-card {
  width: 380px;
  height: 460px; /* 调整高度，移除配送信息后的高度 */
  border: 1px solid #ccc;
  border-radius: 8px;
  padding: 12px;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 10px;
  box-shadow: 0 0 4px rgba(0, 0, 0, 0.1);
}

.food-img {
  width: 100%;
  height: 220px;
  object-fit: contain; /* 图片完整显示 */
  border-radius: 8px;
  margin-bottom: 12px;
}

.food-info {
  width: 100%;
  flex-grow: 1;
  display: flex;
  flex-direction: column;
}

.food-title {
  font-size: 18px;
  font-weight: bold;
  margin: 0 0 8px 0;
  color: #333;
}

.food-price {
  font-size: 20px;
  color: #e60012;
  margin: 0 0 12px 0;
  font-weight: bold;
}

.favorite-btn {
  background-color: #fff;
  border: 1px solid #ffd100;
  color: #333;
  border-radius: 4px;
  padding: 6px 12px;
  cursor: pointer;
  margin-bottom: 12px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.favorite-btn:hover {
  background-color: #fff9e6;
}

.favorite-btn .text-yellow-500 {
  color: #ffd100;
}

.sales-rating {
  font-size: 14px;
  margin-bottom: 16px;
  color: #666;
}

.rating-star {
  color: #ffcc00;
}

.count-area {
  display: flex;
  align-items: center;
  margin-top: auto;
}

.count-btn {
  background-color: #f5f5f5;
  border: 1px solid #ccc;
  width: 36px;
  height: 36px;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 18px;
  transition: background-color 0.2s;
}

.count-btn:hover {
  background-color: #e6e6e6;
}

.count-input {
  width: 50px;
  height: 36px;
  text-align: center;
  border: 1px solid #ccc;
  margin: 0 6px;
  border-radius: 4px;
}

.add-cart-btn {
  background-color: #ffd100;
  color: #333;
  border: none;
  border-radius: 4px;
  padding: 8px 16px;
  cursor: pointer;
  margin-left: 12px;
  font-weight: bold;
  transition: background-color 0.2s;
  flex-grow: 1;
}

.add-cart-btn:hover {
  background-color: #ffc400;
}

.add-cart-btn.loading {
  background-color: #e0e0e0;
  cursor: not-allowed;
}

.add-cart-btn.loading::after {
  content: "加载中...";
}
</style>